var formatSelectString = '';
var linkEditString     = '';

function editInit(topicID) {
	$('editID').value = topicID;
	// Go get selected topic information from server
	x_getSelectedTopic(topicID,returnGetSelectedTopic);
}

function returnGetSelectedTopic(string) {
	$('content1Display').innerHTML = string;
}

// ***** PANEL LOAD FUNCTIONS ************************************
// * These functions are fired when a content panel is accessed.
// * This allows us to reload content, clear content, etc.
// * whenever a tab id clicked (and a content panel viewed).

function content0LoadFunction() {
	// Get selected topic categories for display
	x_getTopicCategories(returnGetTopicCategories);
	
	// Get sources for source drop-down menus
	x_getSources(returnGetSources);	
	
	// Get formats to display in drop-down menus
	x_getSTFormats('select',returnGetSTFormats);
	
	// Clear content1 panel from previous editing
	$('content1Display').innerHTML = '';
	
	// Reset action hidden field to 'add'
	$('action').value = 'add';
}

function returnGetTopicCategories(string) {
	$('stCats').innerHTML = string;
}

function content1LoadFunction() {
	// Set action hidden field to 'edit'
	$('action').value = 'edit';
	
	// Make sure warning message is displayed
	$('content1Warning').style.display = '';
	
	// Get sources for source drop-down menus
	x_getSources(returnGetSources);	
}

function returnGetSTFormats(string) {
	formatSelectString = string;
}

function returnGetSources(string) {
	// Create data source that we will use in our Sources combo-box
	var stringArray = string.split('|');
	var formatID      = stringArray[0];
	var optionContent = stringArray[1];
	
	var optionsArray = optionContent.split('~~');	
	var newOptionsArray = new Array();
	
	for(a=0;a<=(((optionsArray.length)-1));a++) {
		newOptionsArray[a] = [optionsArray[a]];
	}	
	
	// Get sourceData prepped and ready to use 
	// in function renderAddLinkForm below
	Ext.namespace('Ext.sourceData');
	Ext.sourceData.Sources = newOptionsArray;
}

function content2LoadFunction() {
}

// ***** END PANEL LOAD FUNCTION *********************************
function addLinkForm(itemID) {
	string     = '<div class="blueBox" id="linkAddForm'+itemID+'"><input type="hidden" id="itemID'+itemID+'" value="'+itemID+'" />';
	string    += '<div style="margin-left: 20px;">';
	string    += '<table style="width: 100%;"><tr>';
	string    += '<td class="colLeft" style="width: 180px;"><label>Link Title</label></td>';
	string    += '<td><input type="text" id="linkTitleNew'+itemID+'" style="width: 400px;" /></td></tr>';
	string    += '<tr><td class="colLeft"><label>Select Format</label></td>';
	string    += '<td><select style="width: 400px;" id="format'+itemID+'">'+formatSelectString+'</select></td></tr>';
	string    += '<tr><td class="colLeft"><label>Link URL</label></td>';
	string    += '<td><input type="text" id="linkURLNew'+itemID+'" style="width: 400px;" value="http://" /> <a href="#" onClick="gotoURL(\'linkURLNew'+itemID+'\'); return false;">Test Link</a> <a href="#" onClick="makeTinyURL(\'linkURLNew'+itemID+'\'); return false;">Make TinyURL</a></td></tr>';
	string    += '<tr><td class="colLeft" style="vertical-align: top;"><label>Overview Text</label></td>';
	string    += '<td><textarea id="linkOverview'+itemID+'" class="editorAlmostSimple" style="width: 400px; height: 80px;"></textarea></td></tr>';
	string    += '<tr><td class="colLeft" style="vertical-align: top;"><label>Link Content</label></td>';
	string    += '<td><textarea id="linkContentBox'+itemID+'" name="linkContentBox'+itemID+'" class="editorAdvanced" style="width: 100%; height: 250px;"></textarea></td></tr>';
	string    += '<tr><td class="colLeft"><label>Source</label></td>';
	string    += '<td><input type="text" id="linkSource'+itemID+'" style="width: 400px;" /></td></tr>';
	string    += '<tr><td class="colLeft"><label>PDF File</label></td>';
	string    += '<td><input type="text" id="PDFFile'+itemID+'" style="width: 400px;" /></td>';
	string    += '</tr></table>';
	string    += '<div style="float: left; margin-left: 190px; margin-top: 5px;">';
	string    += '<input type="button" class="buttonBig buttonSaveBig" onClick="linkSave('+itemID+');" value="Save" title="Save link" />';
	string    += '&nbsp;<input type="button" id="buttonCancel'+itemID+'" class="buttonBig buttonCancelBig" onClick="cancelLink('+itemID+');" value="Cancel" title="Cancel" /></div>';
	string    += '<div style="float: left;" id="statusDiv'+itemID+'"></div>';
	string    += '<div style="clear: left;"></div>';
	string    += '</div></div>';
	
	return string;
}

function addTopic() {
	$('buttonNew').style.display = 'none';
	new Effect.SlideDown('formNewTopicTitle', {direction: 'top', duration: .3});
}

function renderAddLinkForm(itemID) {
	var formContainerID = 'addLinkFormContainer'+itemID;
	
	// Close any other link forms that may be open
	var linkForms = document.getElementsByClassName('addLinkFormContainer');
	for(i = 0; i < linkForms.length; i++) {		
	    linkForms[i].innerHTML = '';
	}
	
	formString = addLinkForm(itemID);
	
	var store = new Ext.data.SimpleStore({
        fields: ['source'],
        data : Ext.sourceData.Sources
    });
    var combo = new Ext.form.ComboBox({
        store: store,
        displayField:'source',
        typeAhead: true,
        mode: 'local',
        triggerAction: 'all',
        emptyText:'Select a source...',
        selectOnFocus:true,
        resizable:true,
        shadow: false,
        handleHeight: 12
    });
    	
	$(formContainerID).innerHTML    = formString;
	
	// Activate the TinyMCE WYSIWYG editor on textarea id=linkContentBox
	var mceControl = 'linkContentBox'+itemID;
	tinyMCE.execCommand('mceAddControl',true, mceControl);
	
	$('catTitle'+itemID).className  = 'hiLiteCat';
	$('row'+itemID).style.borderTop = '2px solid #F9F97C';
	//new Effect.SlideDown(formContainerID, {direction: 'top', duration: .3});
	
	combo.applyTo('linkSource'+itemID);
}

function renderEditLinkForm(linkEditString) {
	editStringArray = linkEditString.split('|');
	
	var lTitle    = editStringArray[0];
	var lSource   = editStringArray[1];
	var lURLTitle = editStringArray[2];
	var lOverview = editStringArray[3];
	var lContent  = editStringArray[4];
	var lURLPDF   = editStringArray[5];  
	var formatID  = editStringArray[6];
	var itemID    = editStringArray[7];
	
	var formContainerID = 'editLinkFormContainer'+itemID;
	
	// Close any other link forms that may be open
	var linkForms = document.getElementsByClassName('editLinkFormContainer');
	for(i = 0; i < linkForms.length; i++) {		
	    linkForms[i].innerHTML = '';
	}
	
	formString = addLinkForm(itemID);
	
	var store = new Ext.data.SimpleStore({
        fields: ['source'],
        data : Ext.sourceData.Sources
    });
    var combo = new Ext.form.ComboBox({
        store: store,
        displayField:'source',
        typeAhead: true,
        mode: 'local',
        triggerAction: 'all',
        emptyText:'Select a source...',
        selectOnFocus:true,
        resizable:true,
        shadow: false,
        handleHeight: 12
    });
    
	$(formContainerID).innerHTML    = formString;
	$('linkTitle'+itemID).className  = 'hiLiteLink';
	$('rowLink'+itemID).style.borderTop = '2px solid #F9F97C';
	
	combo.applyTo('linkSource'+itemID);
	    
	// Assign form field values
	$('linkTitleNew'+itemID).value = lTitle;
	$('linkSource'+itemID).value   = lSource;
	$('linkURLNew'+itemID).value   = lURLTitle;
	$('linkOverview'+itemID).value = lOverview;	
	$('PDFFile'+itemID).value      = lURLPDF;
	
	// Activate the TinyMCE WYSIWYG editor on textarea id=linkContentBox
	var mceControl = 'linkContentBox'+itemID;
	mceControl.className = 'editorAdvanced';
	tinyMCE.execCommand('mceAddControl',true,mceControl);
	var edInst = tinyMCE.getInstanceById(mceControl)
	
	// And add content to WYSIWYG editor control
	edInst.getBody().innerHTML = lContent+'&nbsp;';	
				
	var formatOptions = $('format'+itemID).options;
	for(a=0;a<formatOptions.length;a++) {
		if ($('format'+itemID).options[a].value == formatID) {
			$('format'+itemID).options[a].selected = true;
		}
	}	
}

function linkEdit(linkID,formatID) {
	// Set action
	$('action').value = 'edit';
	// Get link data
	x_linkEdit(linkID,returnLinkEdit);
}

function returnLinkEdit(string) {
	// Render the edit form
	renderEditLinkForm(string);	
}

function cancelLink(itemID) {
	var doAction = $('action').value;
	if (doAction == 'add') {
		$('row'+itemID).style.borderTop = '';
		$('catTitle'+itemID).className = '';
		var formContainerID = 'addLinkFormContainer'+itemID;
		var newItemID = itemID;		
	} else if (doAction == 'edit') {
		var newItemID = 'Link'+itemID;
		$('row'+newItemID).style.borderTop = '';
		var formContainerID = 'editLinkFormContainer'+itemID;
		$('linkTitleNew'+itemID).className  = ''; 
	}	
	// Remove tinyMCE WYSIWYG editor from textarea id=linkContentBox
	var mceControl = 'linkContentBox'+itemID;
	tinyMCE.execCommand('mceFocus', false, mceControl);  
	tinyMCE.execCommand('mceRemoveControl', false, mceControl); 
	
	rowHoverControls(newItemID,'off','');
	$(formContainerID).innerHTML = '';
}

function linkSave(itemID) {
	var doAction = $('action').value;
	
	var linkTitle = $('linkTitleNew'+itemID).value;
	var linkURL   = $('linkURLNew'+itemID).value;
	var linkOverview = $('linkOverview'+itemID).value;
	var linkContent  = tinyMCE.getContent('linkContentBox'+itemID);
	var linkSource   = $('linkSource'+itemID).value;
	if (linkSource == 'Select a source...') {
		linkSource = '';
	}
		
	var format   = $('format'+itemID).options;
	var formatID = format[format.selectedIndex].value;
	var PDFFile  = $('PDFFile'+itemID).value; 

	var phpString = linkTitle+'|'+linkURL+'|'+linkOverview+'|'+linkContent+'|'+linkSource+'|'+formatID+'|'+itemID+'|'+PDFFile;
	
	if (doAction == 'add') {
		x_linkSave(phpString,'add',returnLinkSave);
		var message = 'Link has been added.';	
		
		// Change CANCEL button text to say I'm Done
		$('buttonCancel'+itemID).value = 'I\'m Done';
		
		// Display confirmation message
		var statusDiv = 'statusDiv'+itemID;
		updateStatus(message,'success',statusDiv);
		
		// Reset form
		$('linkTitleNew'+itemID).value = '';
		$('linkURLNew'+itemID).value   = 'http://';
		$('linkOverview'+itemID).value = '';
		$('linkSource'+itemID).value   = '';
		$('format'+itemID).options[0].selected = true;
		$('PDFFile'+itemID).value      = '';
	} else {
		x_linkSave(phpString,'edit',returnLinkEditSave);
		var message = 'Link has been edited.';
		
		// Close edit window
		cancelLink(itemID);
	}	
}

function returnLinkEditSave(string) {
	var stringArray = string.split('|');
	var itemID  = stringArray[0];
	var content = stringArray[1];		
	
	$('linkContent'+itemID).innerHTML = content;
}

function returnLinkSave() {
}

// ***** ADD NEW SELECTED TOPIC FUNCTIONS ************************

function cancelTopic() {
	// Roll up form
	new Effect.SlideUp('formNewTopicTitle', {direction: 'top', duration: .3});
	
	// Clear all form fields
	$('stTitle').value = '';
	
	// Turn 'New' button back on
	$('buttonNew').style.display = 'block';
}

function saveTitle() {
	var title = $('stTitle').value;
	if ( (title != 'Selected Topic Title...') && (title != '') ) {
		x_saveTitle(title,'add',returnSaveTitle);
	}
}

function returnSaveTitle(statusString) {
	var stringArray = statusString.split('|');
	var what    = stringArray[0];
	var content = stringArray[1];
	if (what == 'error') {
		$('errorTitle').innerHTML = '<span color="red">'+content+'</span>';
	} else {
		// Clear new title form
		cancelTopic(); 
		// Get new topic category list
		x_getTopicCategories(returnGetTopicCategories);
		
		/*
		$('stTitleDiv').innerHTML = '<h1 id="stTitle" onClick="editTitle();" style="cursor: pointer;">'+$('stTitle').value+'</h1>';
		$('errorTitle').innerHTML = '';
		$('stID').value = content;
		
		// Turn on format entry form if !on
		if ($('addNewFormatContainer').style.display == 'none') {
			$('addNewFormatContainer').style.display = 'block';
		}
		*/
	}
}

function editTitle() {
	var title = $('stTitle').innerHTML;
	$('stTitleDiv').innerHTML = '<input type="text" style="width: 400px; margin-bottom: 10px;" id="stTitle" class="inputBigTitle" onBlur="editTitleConfirm(this.value);" value="'+title+'" />';
}

function editTitleConfirm(title) {
	var catID = $('stID').value;
	x_saveTitle(title,'edit',catID,returnSaveTitle);
}

function formatSave(formatID,formatTitle) {
	if ( (formatTitle != 'Add A Format...') && (typeof(formatTitle) != 'undefined') ) {
		formString = renderAddLinkForm(formatID,0,'add');
		
		var string = '<div style="margin-bottom: 20px;" id="linkContainer'+formatID+'">';
		
		string    += '<div id="formatTitleContainer'+formatID+'">';
		string    += '<div style="float: left; width: 50px;">';
		string    += '<a href="#" onClick="formatEdit('+formatID+'); return false;"><img src="images/buttonEditBig.gif" style="border: none;" alt="Edit" /></a>&nbsp;';
		string    += '<a href="#" onClick="confirmDelete('+formatID+'); return false;"><img src="images/buttonDeleteBig.gif" style="border: none;" alt="Delete" /></a>';
		string    += '</div>';
		string    += '<div style="float: left;">';
		string    += '<h3 style="margin-bottom: 15px;">'+formatTitle+'</h3>';
		string    += '</div><div style="clear: left;"></div></div>';
		string    += '<div id="formatTitleEditContainer'+formatID+'"></div>';
		string    += formString;
		string    += '</div>';		
		
		var store = new Ext.data.SimpleStore({
	        fields: ['source'],
	        data : Ext.sourceData.Sources
	    });
	    var combo = new Ext.form.ComboBox({
	        store: store,
	        displayField:'source',
	        typeAhead: true,
	        mode: 'local',
	        triggerAction: 'all',
	        emptyText:'Select a source...',
	        selectOnFocus:true,
	        resizable:true,
	        shadow: false,
	        handleHeight: 12
	    });
	
		// Append a div for this new format
		var formatContainer = $('stFormatContainer');
		var newFormatDiv = document.createElement('div');
		
		newFormatDiv.id = 'formatContainer'+formatID;
		newFormatDiv.innerHTML = string;
				
		formatContainer.appendChild(newFormatDiv);
		
		// Set source combo box
		combo.applyTo('linkSource'+formatID);
		
		// Reset format select menu
		$('formatSelect').selectedIndex = 0;		
	}	
}

function formatEdit(topicID,origFormatID) {
	// Turn off format <h3>
	$('catTitle'+origFormatID).style.display = 'none';
	
	// Turn on format edit DIV
	$('formatEditDiv'+origFormatID).style.display = 'block';
	
	var selectString  = '<select id="formatEditSelect'+origFormatID+'" class="formatEditSelect" size="1">';
	selectString += formatSelectString;
	selectString += '</select>&nbsp;';
	selectString += '<input type="button" onClick="formatEditConfirm('+topicID+','+origFormatID+');" value="Edit" /> <input type="button" onClick="formatEditCancel('+origFormatID+');" value="Cancel" /> ';
	
	$('formatEditDiv'+origFormatID).innerHTML = selectString;	
}

function formatEditConfirm(topicID,origFormatID) {
	var newFormat   = $('formatEditSelect'+origFormatID).options;
	var newFormatID = newFormat[newFormat.selectedIndex].value;
	x_editFormat(newFormatID,origFormatID,topicID,returnFormatEditConfirm);
}

function returnFormatEditConfirm(topicID) {
	// Repaint entire screen
	editInit(topicID);
}

function formatEditCancel(formatID) {
	// Turn on format <h3>
	$('catTitle'+formatID).style.display = 'block';
	
	// Turn off format edit DIV
	$('formatEditDiv'+formatID).style.display = 'none';
	$('formatEditDiv'+formatID).innerHTML = '';
}

function returnLinkSave_old(string) {
	var stringArray = string.split('|');
	var formatID = stringArray[0];
	var linkID   = stringArray[1];
	var content  = stringArray[2];
	
	// Append a div for this new link
	var linkContainer = $('linkContainer'+formatID);
	var newLinkDiv = document.createElement('div');
	
	newLinkDiv.id = 'link'+linkID;
	newLinkDiv.innerHTML = content;
	
	var linkAddForm = $('linkAddForm'+formatID);
	linkContainer.insertBefore(newLinkDiv,linkAddForm);
	
	// Clear link add form
	clearLinkForm(formatID);
}

function linkDelete(linkID) {
	x_linkDelete(linkID,returnLinkDelete);
}

function returnLinkDelete(linkID) {
	if ($('action').value == 'add') {
		var removeLinkNode = $('row'+linkID);
	} else if ($('action').value == 'edit') {
		var removeLinkNode = $('rowLink'+linkID);
	}	
	removeLinkNode.style.display = 'none';
}

// ***** END ADD NEW SELECTED TOPIC FUNCTIONS ********************

// ***** DELETE SELECTED TOPIC FUNCTIONS *************************

function deleteSelectedTopic(topicID) {
	x_deleteSelectedTopic(topicID,showSelectedTopic);
}

function showSelectedTopic(string) {
	$('stCats').innerHTML = string;
}

// ***** END DELETE SELECTED TOPIC FUNCTIONS *********************

function clearLinkForm(formatID) {
	$('linkTitleNew'+formatID).value = '';
	$('linkURLNew'+formatID).value = 'http://';
	$('linkOverview'+formatID).value = '';
}

function getSources(formatID) {
	x_getSources(formatID,returnGetSources);
}